package demo_01;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class UpdateDemo_01 {
    private String sql;

    public UpdateDemo_01(String sql) {
        this.sql = sql;
    }

    public UpdateDemo_01() {
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

    public void  updatetbl(String sql) {
        String driver = "com.mysql.jdbc.Driver";
//        数据库名在localhost上存在才可以连接
        /*String url = "jdbc:mysql://10.25.112.27:3306/jdbc" +
                "?useUnicode=true&characterEncoding=utf-8";
                孙文彩电脑的数据库*/
        String url = "jdbc:mysql://localhost:3306/jdbc" +
                "?useUnicode=true&characterEncoding=utf-8";
        String user = "root";
        String password = "admin";
//        声明数据库连接需要的参数
        try {
            Class.forName(driver);//加载驱动类
        } catch (ClassNotFoundException e) {
            System.out.println("驱动类不存在!");
            e.printStackTrace();
        }
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = DriverManager.getConnection(url,user,password);
            //根据用户提供的参数获取数据库连接
            stmt = conn.createStatement();
            int r = stmt.executeUpdate(sql);//执行修改,并返回受影响的行数
            if (r>0){
                System.out.println("执行成功");
            }else {
                System.out.println("执行失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
            if (conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
